package com.sys.basics.config.quartz;

import cn.hutool.core.util.ObjectUtil;
import com.sys.basics.dao.SysScheduleJobDao;
import com.sys.basics.entity.SysScheduleJob;
import com.sys.basics.utils.quartz.ScheduleUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "spring.quartz", name = "enable", havingValue = "true")
public class ApplicationStartQuartzJobListener implements ApplicationListener<ApplicationStartedEvent> {

    @Autowired
    SysScheduleJobDao sysScheduleJobDao;

    @Autowired
    private Scheduler scheduler;

    /**
     * 初始启动quartz
     */
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        log.info(">>>初始化数据库存在的定时任务<<<");

        List<SysScheduleJob> scheduleJobList = sysScheduleJobDao.selectList(null);
        for (SysScheduleJob scheduleJob : scheduleJobList) {
            try {
                CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId());
                // 如果不存在，则创建
                if (ObjectUtil.isNull(cronTrigger)) {
                    ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
                } else {
                    ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
                }
            } catch (SchedulerException e) {
                log.error(">>>初始化数据库存在的定时任务时发生错误<<< {}", e);
            }
        }
    }
}
